<?php
/**
 * 材料申请
 * (model)
 */
namespace App\Models\Product;

use App\Models\Basics\SupplierM;
use Illuminate\Database\Eloquent\Model;

class ProductMaterialApply extends Model{

    protected $table = 'product_material_apply';

    protected $guarded = [];

    const AUDIT_NO = 1;      //未审核
    const AUDIT_SUCCESS = 2; //审核通过
    const AUDIT_REJECT = 3;  //审核拒绝
    public static $_auditStatus = [
        self::AUDIT_NO      => '未审核',
        self::AUDIT_SUCCESS => '已通过',
        self::AUDIT_REJECT  => '已拒绝',
    ];

    const STATUS_YES = 1; //启用
    const STATUS_NO  = 2; //停用
    public static $_status = [
        self::STATUS_YES => '已使用',
        self::STATUS_NO  => '未使用',
    ];

    const FLAG_YES = 1; //已入库
    const FLAG_NO  = 2; //未入库
    public static $flag_status = [
        self::FLAG_YES => '是',
        self::FLAG_NO  => '否',
    ];

    public function material(){
        return $this->belongsTo(ProductMaterial::class,'material_id');
    }
    public function supplier(){
        return $this->belongsTo(SupplierM::class,'supplier_id');
    }

    public static function options($where = []){
        $query = $where ? self::query()->where(formatCondition($where)) : self::query();
        $res = $query->get()->map(function ($model){
            return collect(['material' => $model->material_code.'-'.$model->title,
                'id' => $model->id]);
        });
        return $res->pluck('material','id');
    }

    /**
     * 寻源数量
     * @param $month
     * @param $originStatus
     * @return int
     */
    public static function getOriginSum($month, $originStatus){
        return self::query()
            ->where('apply_month',$month)
            ->where('origin_status',$originStatus)
            ->count() ?? 0;
    }

    /**
     * 超期数量（超期,超过寻源期限的申请单数）
     * @param $month
     * @param $originStatus
     * @return int
     */
    public static function getOverdueSum($month){
        return self::query()
                ->where('apply_month',$month)
                ->whereColumn('origin_time', '>', 'cylce')
                ->count() ?? 0;
    }

    protected static function boot()
    {
        parent::boot();

        static::deleting(function ($model){
            if($model->status == 1){
                throw new \Exception('材料已启用请勿删除');
            }
            $count = ProductSupplierM::query()->where('material_id',$model->id)->count();
            if($count > 0){
                throw new \Exception('请先删除所有关联的材料说明书');
            }
        });
    }
}
